package com.ht.api.service;

import java.io.File;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import com.ht.api.db.util.WxFileUtils;
import com.ht.api.open.OpenUtil;
import com.ht.api.open.TokenService;
import com.ht.api.oss.AliyunOssUploadUtils;
import com.ht.api.util.Mp3Util;

import cn.hutool.core.io.FileUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 企业微信service
 * @author asq
 * @createTime 2025年4月7日 19:01:54
 */
@Slf4j
public class WwxService {
	/** 接口ID：配置客户联系「联系我」方式 */
	private static final long API_ID_CONTACT_WAY_ADD = 1900130323056955392L;
	/** 接口ID：删除企业已配置的「联系我」方式 */
	private static final long API_ID_CONTACT_WAY_DEL = 1900131364737519616L;
	/** 获取token的服务类 */
	private static TokenService tokenService = SpringUtil.getBean(TokenService.class);
	
	/** 消息类型简略描述 */
	private static Map<String, String> msgMap = new HashMap<>();
	static {
		msgMap.put("image", "[图片]");
		msgMap.put("voice", "[语音]");
		msgMap.put("video", "[视频]");
		msgMap.put("shortvideo", "[小视频]");
		msgMap.put("file", "[文件]");
		msgMap.put("location", "[位置]");
		msgMap.put("link", "[链接]");
		msgMap.put("business_card", "[名片]");
		msgMap.put("miniprogram", "[小程序]");
		msgMap.put("msgmenu", "[菜单]");
		msgMap.put("channels_shop_product", "[视频号商品]");
		msgMap.put("channels_shop_order", "[视频号订单]");
		msgMap.put("merged_msg", "[聊天记录]");
		msgMap.put("channels", "[视频号]");
		msgMap.put("meeting", "[会议]");
		msgMap.put("calendar", "[日程]");
		msgMap.put("note", "[笔记]");
	}

    public static String getTempImageMediaId (String appId, String url) {
        return getTempMediaId(appId, "image", url);
    }

    public static String getTempVideoMediaId (String appId, String url) {
        return getTempMediaId(appId, "video", url);
    }

    public static String getTempVoiceMediaId (String appId, String url) {
        return getTempMediaId(appId, "voice", url);
    }

    public static String getTempFileMediaId (String appId, String url) {
        return getTempMediaId(appId, "file", url);
    }

	/**
	 * 上传企微临时素材
	 * @param appId
	 * @param type
	 * @param url
	 * @return
	 */
    public static String getTempMediaId (String appId, String type, String url) {
        JSONObject fileParam = JSONUtil.createObj();
        fileParam.set("type", type);
        fileParam.set("oss_url", url);
        String imageResult = OpenUtil.call(appId, 1891784559327055872L, fileParam);
        String imageMediaId = JSONUtil.parseObj(imageResult).getStr("media_id");

        return imageMediaId;
    }

    public static String getAttachmentImageMediaId (String appId, String url) {
        return getAttachmentMediaId(appId, "image", url);
    }

    public static String getAttachmentVideoMediaId (String appId, String url) {
        return getAttachmentMediaId(appId, "video", url);
    }

	/**
	 * 上传企微附件
	 * @param appId
	 * @param type
	 * @param url
	 * @return
	 */
    public static String getAttachmentMediaId (String appId, String type, String url) {
        JSONObject fileParam = JSONUtil.createObj();
        fileParam.set("media_type", type);
        fileParam.set("attachment_type", 1);
        fileParam.set("oss_url", url);
        String imageResult = OpenUtil.call(appId, 1894004243472453632L, fileParam);
        String imageMediaId = JSONUtil.parseObj(imageResult).getStr("media_id");

        return imageMediaId;
    }

	/**
	 * 获取客户发送的消息
	 * @param msg
	 * @return
	 */
    public static String formatMsg(JSONObject msg) {
    	String msgtype = msg.getStr("msgtype");
		if ("text".equals(msgtype)) {
			return msg.getByPath("text.content", String.class);
		} else {
			String shortMsg = msgMap.get(msgtype);
			if (shortMsg != null) {
				return shortMsg;
			} else {
				return "";
			}
		}
	
	}

	/**
	 * 获取客户发送的消息
	 * @param msg
	 * @return
	 */
    public static String formatMsg(JSONObject msg, String typeField, String contentPath) {
    	String msgtype = msg.getStr(typeField);
		if ("text".equals(msgtype)) {
			return msg.getByPath(contentPath, String.class);
		} else {
			String shortMsg = msgMap.get(msgtype);
			if (shortMsg != null) {
				return shortMsg;
			} else {
				return "";
			}
		}
	}
	
	/**
	 * 通过是否能生成“联系我”，来判断客服是否实名
	 * @param appid 应用ID
	 * @param entity 通迅录读取成员返回结果对象
	 * @return 
	 */
	public static void setRealnameStatus(String appid, JSONObject entity) {
		if (entity.getInt("status") != 1) {
			return;
		}
		
		// 调用企微接口
		JSONObject wwxParam = JSONUtil.createObj();
		wwxParam.set("type", 1);
		wwxParam.set("scene", 2);
		wwxParam.set("user", Arrays.asList(entity.getStr("userid")));
		try {
			String str = OpenUtil.call(appid, API_ID_CONTACT_WAY_ADD, wwxParam);
			JSONObject obj = JSONUtil.parseObj(str);
			if (obj.getInt("errcode") == 0) {
				// 调用企微接口，删除刚刚创建的联系我
				JSONObject wwxParamDel = JSONUtil.createObj().set("config_id", obj.getStr("config_id"));
				String str2 = OpenUtil.call(appid, API_ID_CONTACT_WAY_DEL, wwxParamDel);
				JSONObject obj2 = JSONUtil.parseObj(str2);
				if (obj2.getInt("errcode") != 0) {
					log.info("[test-contact-way]企微初始化时删除刚刚创建的联系我失败：{}，请求参数：{}", obj.getStr("errmsg"), 
							wwxParamDel.toString());
				}

				// 标记为已实名
				entity.set("realname_status", 1); 
				log.info("[test-contact-way]企微初始化时测试联系我成功，将被标记为已实名，请求参数：{}", wwxParam.toString());
			} else if (obj.getInt("errcode") == 40098) {
				// {"errcode":40098,"errmsg":"user real name has not been verified"}
				// 标记为未实名
				entity.set("realname_status", 0); 
				log.info("[test-contact-way]企微初始化时测试联系我返回40098，将被标记为未实名，请求参数：{}", wwxParam.toString());
			} else {
				log.info("[test-contact-way]企微初始化时创建联系我失败：{}，请求参数：{}", obj.getStr("errmsg"), wwxParam.toString());
			}
		} catch (Exception e) {
			log.error("[test-contact-way]企微初始化时创建联系我发生异常：{}，请求参数：{}", e.getMessage(), wwxParam.toString(), e);
		}
	}

    /**
     * 下载素材，并上传到阿里云
     * @param mediaId 素材ID
     * @param ext 扩展名
     * @return
     */
    public static String uploadFileToAliyun(String mediaId) {
    	// 下载素材
    	String url = "https://qyapi.weixin.qq.com/cgi-bin/media/get?access_token=%s&media_id=%s";
		String token = tokenService.getToken(1868916871932284928L, "1876990838014349312");
		File file = WxFileUtils.downFile(String.format(url, token, mediaId));
		String ext = FileUtil.extName(file);
		
		// 处理语音文件
		File convertFile = file;
		if ("amr".equals(ext)) {
			convertFile = Mp3Util.convertAmrToMp3(file);
			ext = FileUtil.extName(convertFile);
		}
		
		// 上传
		String path = null;
		try {
			log.info("上传企业微信素材到阿里云，素材ID：{}，扩展名：{}", mediaId, ext);
			path = AliyunOssUploadUtils.uploadFile(convertFile, mediaId + "." + ext);
		} catch (Exception e) {
			log.error("上传企业微信素材文件到阿里云出现异常：{}", e.getMessage(), e);
		}
		
		// 删除临时文件
		try {
			if (!file.delete()) {
		        file.deleteOnExit();
		    }
			if (!convertFile.delete()) {
				convertFile.deleteOnExit();
			}
			file.getParentFile().delete();
			
			log.info("上传企业微信素材文件到阿里云成功，已删除临时文件：{}", mediaId + "." + ext);
		} catch (Exception e) {
			log.info("上传企业微信素材文件到阿里云成功，删除临时文件出现异常：{}", e.getMessage(), e);
		}
    	
    	return path;
    }
}
